package cn.tedu.boot1.controller;

import cn.tedu.boot1.entity.User;
import cn.tedu.boot1.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody

    public String reg(User user){
        //soutp 返回参数值
        System.out.println("user = " + user);

        try (Connection conn = DBUtils.getConn()){
            String sql = "insert into user values(null,?,?,?)";
            //创建执行SQL语句对象
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换?
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功";
    }

    @RequestMapping("/login")
    @ResponseBody

    public String login(User user){
        System.out.println("user = " + user);
        try (Connection conn = DBUtils.getConn()){
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                if (user.getPassword().equals(rs.getString(1))){
                    return "登陆成功!";
                }
            }
            return "登陆错误!";
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "登陆成功~";
    }
}
